package com.heny.demo.strategy;

import com.heny.demo.entity.TurnPoint;
import org.apache.poi.ss.usermodel.*;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class XLSXFileImportStrategy implements FileImportStrategy {
    @Override
    public List<TurnPoint> importData(File file) {
        List<TurnPoint> turnPoints = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file)) {
            Workbook workbook = WorkbookFactory.create(fis); // 创建 Workbook 对象
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

            // 遍历工作表中的每一行
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过表头（如果存在）

                // 解析每一列的数据
                String index = row.getCell(0).getStringCellValue().trim(); // 索引字段
                double x = row.getCell(1).getNumericCellValue(); // X 坐标
                double y = row.getCell(2).getNumericCellValue(); // Y 坐标
                double z = row.getCell(3).getNumericCellValue(); // Z 坐标

                // 创建 TurnPoint 实体
                TurnPoint turnPoint = new TurnPoint();
                turnPoint.setIndex(index);
                turnPoint.setCoordinate(createPoint(x, y, z)); // 使用 JTS Point 初始化
                turnPoints.add(turnPoint);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return turnPoints;
    }

    // 工厂方法：创建 JTS Point 对象
    private Point createPoint(double x, double y, double z) {
        GeometryFactory geometryFactory = new GeometryFactory();
        Coordinate coordinate = new Coordinate(x, y, z);
        return geometryFactory.createPoint(coordinate);
    }
}